/*
编写 : Hexh
时间 : 2012-5-25 17:19:10
*/
using System;
using System.Collections.Generic;
using HMIS.FrameWork.DomainBase;
using HMIS.FrameWork.Repository;
using HMIS.FrameWork.Repository.Nhb;
using FsCarInfo;
using HMIS.Infrastructure.Core.Entities;
using HMIS.Infrastructure.Core.Repositories.Impl;
using System.Threading;
using HMIS.FrameWork.Repository.NHb;

namespace FsCarInfo.Core.Entity.IRespositories.Impl
{
    /// <summary>
    ///	 the repository of FsIntlVehicleAppl
    /// </summary>
    public class FsIntlVehicleApplRepositoryImpl : RepositoryNhbImpl<FsIntlVehicleAppl>, IFsIntlVehicleApplRepository
    {

        /// <summary>
        /// 判断是否已经有重复值
        /// </summary>
        /// <param name="fieldName">行名</param>
        /// <param name="fieldValue">值</param>
        /// <param name="id">ID列的值</param>
        /// <returns>True， False</returns>
        public bool IsFieldExist(string fieldName, string fieldValue, string id)
        {
            return base.IsFieldExist(fieldName, fieldValue, id, null);
        }

        // <summary>
        /// 判断是否已经有重复值
        /// </summary>
        /// <param name="fieldName">行名</param>
        /// <param name="fieldValue">值</param>
        /// <param name="id">ID列的值</param>
        /// <param name="where">Where 条件</param>
        /// <returns>True， False</returns>
        public bool IsFieldExistWhere(string fieldName, string fieldValue, string id, string where)
        {
            return base.IsFieldExist(fieldName, fieldValue, id, where);
        }

        /// <summary>
        /// 查询 FsIntlVehicleAppl
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="start">分页开始</param>
        /// <param name="limit">分页大小</param>
        /// <param name="sort">排序条件</param>
        /// <param name="dir">排序方向</param>
        /// <param name="filters">筛选条件</param>
        /// <param name="total">返回记录条数</param>
        /// <returns>返回记录集</returns>
        public IList<FsIntlVehicleAppl> GetPlist(string query, string state, int start, int limit, string sort, string dir, List<DataFilter> filters, out long total)
        {
            // filter
            var strFilter = base.GetHqlstrByExtFilter(filters, "t");

            // 修改查询条件ID1 ID2
            string strQuery = string.IsNullOrEmpty(query) ? strFilter :
                "( t.ApplUser.Name = :query or t.IntlVehicle.CarNo like :carno ) "
                    + (string.IsNullOrEmpty(strFilter) ? string.Empty : " and " + strFilter);

            // 增加状态
            strQuery = string.IsNullOrEmpty(state) ? strQuery :
                "( t.State = :state ) " + (string.IsNullOrEmpty(strQuery) ? string.Empty : " and " + strQuery);

            // sort
            string strSort = string.IsNullOrEmpty(sort) ? string.Empty : " order by t." + sort + " " + dir;

            // 修改关联查询条件 OuterColumn
            string strSql = @" from FsIntlVehicleAppl as t 
									inner join fetch t.ApplUser
									inner join fetch t.IntlVehicle"
                + (string.IsNullOrEmpty(strQuery) ? string.Empty : " where " + strQuery);

            // 查询
            var selQuery = Session.CreateQuery(@"select t " + strSql + strSort);
            var totQuery = Session.CreateQuery(@"select count(*) " + strSql.Replace(" join fetch ", " join "));

            // 设置查询条件
            if (!string.IsNullOrEmpty(query))
            {
                selQuery.SetString("query", query);
                totQuery.SetString("query", query);
                selQuery.SetString("carno", "%" + query + "%");
                totQuery.SetString("carno", "%" + query + "%");
            }
            if (!string.IsNullOrEmpty(state))
            {
                selQuery.SetString("state", state);
                totQuery.SetString("state", state);
            }

            // 分页
            if (limit > 0)
                selQuery.SetFirstResult(start).SetMaxResults(limit);

            // 汇总并返回
            total = totQuery.UniqueResult<long>();
            return selQuery.List<FsIntlVehicleAppl>();
        }

        /// <summary>
        /// 返回超时的用车信息
        /// </summary>
        /// <returns></returns>
        public IList<FsIntlVehicleAppl> GetOverTimePlist()
        {
            // 修改关联查询条件 OuterColumn
            string strSql = @"select t from FsIntlVehicleAppl as t 
									inner join fetch t.ApplUser
									inner join fetch t.IntlVehicle
								where t.State = :State and t.ExpRetTime < :currentTime and t.SmsTime < :SMSTIME";
            // 查询
            var selQuery = Session.CreateQuery(strSql);
            // 条件
            selQuery.SetDateTime("currentTime", System.DateTime.Now);
            selQuery.SetParameter("State", FsIntlVehicleApplState.Processing);
            // 设置发送间隔
            selQuery.SetDateTime("SMSTIME", System.DateTime.Now.AddMinutes(-30));
            // 返回
            return selQuery.List<FsIntlVehicleAppl>();
        }

        /// <summary>
        /// 扫描超时记录并发送短信
        /// </summary>
        public void SendOverTimeSms()
        {
            InfraSmsRepositoryImpl smsRep = new InfraSmsRepositoryImpl();
            InfraApproveLogRepositoryImpl apprlogRep = new InfraApproveLogRepositoryImpl();

            IList<FsIntlVehicleAppl> otList = this.GetOverTimePlist();
            foreach (FsIntlVehicleAppl appl in otList)
            {
                long total;
                string smsContent = "[用车超时警告!]\n" + appl.ToSmsString();
                List<string> sendList = new List<string>();
                // 发送申请人和审批人
                sendList.Add(appl.ApplUser.Mobitl);
                IList<InfraApproveLog> approveList = apprlogRep.GetPlist(appl.Id, "", 0, 0, "", "", null, out total);
                foreach (InfraApproveLog logstep in approveList)
                {
                    if (sendList.IndexOf(logstep.User.Mobitl) < 0)
                        sendList.Add(logstep.User.Mobitl);
                }
                foreach (string mobile in sendList)
                {
                    if (!String.IsNullOrEmpty(mobile))
                    {
                        smsRep.SendSms(appl.Id, mobile, smsContent);
                        Thread.Sleep(200);	//等待500秒再发下一条
                    }
                }
                // 更新最近发送短信的时间
                appl.SmsTime = System.DateTime.Now;
                SaveOrUpdate(appl);
            }
        }
    }
}
